package com.yonyou.pmclouds.workflow.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.workflow.entity.ProcessDefinitionVO;
import com.yonyou.pmclouds.workflow.util.WorkFlowConst;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import yonyou.bpm.rest.RepositoryService;
import yonyou.bpm.rest.exception.RestException;
import yonyou.bpm.rest.request.repository.ProcessDefinitionModel;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 *  流程模型定义服务类，用于配置审批流
 *  @author zhangzhonghao
 */

@Service
public class ProcessModelDefinitionService {

    private static final String DEFAULT_CATEGORY_CODE = "defaultCategory";

    private static final String DEFAULT_CATEGORY_NAME = "其他";

    private static final String PROCESS_ID = "id";

    @Value("${bpmrest.designerUrl}")
    private String designerUrl;

    /**
     * 创建流程模型
     * @param definitionVO 流程模型
     * @return 流程模型定义
     */
    public ProcessDefinitionVO insertProcessDefinition(ProcessDefinitionVO definitionVO)
            throws BusinessException{
        RepositoryService repositoryService = (RepositoryService)ProcessServiceFactory
                .getProcessService(ProcessServiceFactory.REPOSITORY_SERVICE, definitionVO.getUserId(), definitionVO.getPkTenant());

        // 创建流程模型至云审批
        ProcessDefinitionModel definitionModel = new ProcessDefinitionModel();
        // key值必需以字母或者下划线开头,且不允许重复
        definitionModel.setKey(definitionVO.getBillType() + "_" + UUID.randomUUID().toString());
        // 暂时不做目录维护，使用默认的目录
        definitionModel.setCategory(DEFAULT_CATEGORY_NAME);
        definitionModel.setCategoryCode(DEFAULT_CATEGORY_CODE);

        String processName = definitionVO.getProcessName();
        if(StringUtils.isNotEmpty(definitionVO.getPkOrg()))
            processName = processName +"("+definitionVO.getOrgName()+")";
        definitionModel.setName(processName);
        definitionModel.setTenantId(definitionVO.getPkTenant());
        JsonNode jsonNode;
        try {
            jsonNode = (JsonNode) repositoryService.createProcessDefinitionModel(definitionModel);
            if(jsonNode == null){
                throw new BusinessException(WorkFlowConst.YS_NULL_RESP_MSG);
            }
        }catch (RestException | RuntimeException e){
            throw new BusinessException(e.getMessage());
        }
        if(jsonNode.findValue(PROCESS_ID) != null) {
            Date currentDate = Calendar.getInstance().getTime();
            definitionVO.setProcessKey(definitionModel.getKey());
            definitionVO.setCreationtime(currentDate);
            definitionVO.setModifytime(currentDate);
            definitionVO.setProcessId(jsonNode.findValue(PROCESS_ID).textValue());
            return definitionVO;
        }
        return null;
    }

    public void updateDefinition(ProcessDefinitionVO definitionVO) throws BusinessException{
        ProcessDefinitionModel definitionModel = new ProcessDefinitionModel();
        definitionModel.setKey(definitionVO.getProcessKey());
        // 暂时不做目录维护，使用默认的目录
        definitionModel.setCategory(DEFAULT_CATEGORY_NAME);
        definitionModel.setCategoryCode(DEFAULT_CATEGORY_CODE);
        definitionModel.setName(definitionVO.getProcessName());
        definitionModel.setTenantId(definitionVO.getPkTenant());
        try {
            RepositoryService repositoryService = (RepositoryService)ProcessServiceFactory
                    .getProcessService(ProcessServiceFactory.REPOSITORY_SERVICE, definitionVO.getUserId(), definitionVO.getPkTenant());
            repositoryService.updateProcessDefinitionModel(definitionVO.getProcessId(), definitionModel);
        }catch (RestException | RuntimeException e){
            throw new BusinessException(e.getMessage());
        }
    }

    public boolean deleteDefinition(ProcessDefinitionVO definitionVO) throws BusinessException{
        try {
            RepositoryService repositoryService = (RepositoryService)ProcessServiceFactory
                    .getProcessService(ProcessServiceFactory.REPOSITORY_SERVICE, definitionVO.getUserId(), definitionVO.getPkTenant());
            return repositoryService.deleteProcessDefinitionModel(definitionVO.getProcessId());
        }catch (RestException e){
            throw new BusinessException("删除云审批中的流程模型：" + e.getMessage());
        }
    }

    public String getDesignerUrl(){
        return designerUrl;
    }
}
